package com.cq.hd.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.constant.RedisKeyConstant;
import com.cq.hd.common.entity.MerchantUserInfo;
import com.cq.hd.common.enums.ResponseEnums;
import com.cq.hd.common.enums.biz.*;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.BeanUtils;
import com.cq.hd.common.utils.LocalDateUtil;
import com.cq.hd.common.utils.RedisUtil;
import com.cq.hd.common.utils.StringUtils;
import com.cq.hd.member.api.dto.*;
import com.cq.hd.member.api.vo.*;
import com.cq.hd.member.biz.SmsBiz;
import com.cq.hd.member.config.LockUtils;
import com.cq.hd.member.mapper.*;
import com.cq.hd.member.po.*;
import com.cq.hd.member.service.TbBusinessEnterApplyService;
import com.cq.hd.member.service.TbMerchantBankCardService;
import com.cq.hd.member.service.TbMerchantEnterApplyService;
import com.cq.hd.member.service.TbMerchantService;
import com.cq.hd.order.api.TbOrderItemApi;
import com.cq.hd.order.api.dto.OrderItemDto;
import com.cq.hd.order.api.vo.OrderItemVo;
import com.cq.hd.product.api.TbGoodsApi;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商户表 服务实现类
 * </p>
 *
 * @author mYunYu
 * @since 2023-11-21
 */
@Service
public class TbMerchantServiceImpl extends ServiceImpl<TbMerchantMapper, TbMerchantPo> implements TbMerchantService {

    @Autowired
    private TbBusinessMerchantMapper businessMerchantMapper;

    @Autowired
    private TbBusinessMapper businessMapper;

    @Autowired
    private TbMerchantEnterApplyMapper merchantEnterApplyMapper;

    @Resource
    private TbBusinessEnterApplyService businessEnterApplyService;

    @Autowired
    private TbBusinessEnterApplyMapper businessEnterApplyMapper;

    @Autowired
    private TbMerchantBankCardService merchantBankCardService;

    @Autowired
    private TbMerchantEnterApplyService merchantEnterApplyService;

    @Autowired
    private TbGoodsApi goodsApi;

    @Autowired
    private TbOrderItemApi orderItemApi;

    @Autowired
    private SmsBiz smsBiz;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Page<MerchantPageVo> pageMerchant(MerchantPageDto merchantPageDto) {
        String startTime = merchantPageDto.getStartTime();
        String endTime = merchantPageDto.getEndTime();
        Long businessId = merchantPageDto.getBusinessId();
        if (!StringUtils.isBlank(startTime) && startTime.length() != 19) {
            Throw.isBusinessException("日期格式错误");
        }
        if (!StringUtils.isBlank(endTime) && endTime.length() != 19) {
            Throw.isBusinessException("日期格式错误");
        }

        // 判断是否选择了商家搜索，如果是，则查tb_business_merchant表，否则查tb_merchant表
        if (businessId != null) {
            PageHelper.startPage(merchantPageDto.getPageNum(), merchantPageDto.getPageSize());
            List<MerchantPageVo> merchantPageVos = businessMerchantMapper.listMerchantByDto(merchantPageDto);
            PageInfo<MerchantPageVo> pageInfo = new PageInfo<>(merchantPageVos);
            return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
        }

        PageHelper.startPage(merchantPageDto.getPageNum(), merchantPageDto.getPageSize());
        List<MerchantPageVo> merchantPageVos = baseMapper.listMerchantByDto(merchantPageDto);
        PageInfo<MerchantPageVo> pageInfo = new PageInfo<>(merchantPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public AdminMerchantPageVo details(Long id) {
        TbMerchantPo tbMerchantPo = baseMapper.selectById(id);
        if (tbMerchantPo != null) {
            AdminMerchantPageVo adminMerchantPageVo = new AdminMerchantPageVo();
            BeanUtils.copyProperties(tbMerchantPo, adminMerchantPageVo);

            // 查询商家入驻数据，如果不存在，则查询商家入驻数据
            List<TbMerchantEnterApplyPo> merchantEnterApplyPos = merchantEnterApplyMapper.selectList(new QueryWrapper<TbMerchantEnterApplyPo>()
                    .eq("del_state", 0)
                    .eq("mobile", tbMerchantPo.getMobile())
                    .orderByDesc("create_time"));
            if (!CollectionUtils.isEmpty(merchantEnterApplyPos)) {
                AppMerchantEnterApplyPageVo appMerchantEnterApplyPageVo = new AppMerchantEnterApplyPageVo();
                BeanUtils.copyProperties(merchantEnterApplyPos.get(0), appMerchantEnterApplyPageVo);

                String bankCode = appMerchantEnterApplyPageVo.getBankCode();
                if (!StringUtils.isBlank(bankCode)) {
                    HfBankIdEnum hfBankIdEnum = HfBankIdEnum.typeOfValue(bankCode);
                    if (hfBankIdEnum != null) {
                        appMerchantEnterApplyPageVo.setBankName(hfBankIdEnum.getName());
                    }
                }

                // 法人证件类型
                String legalCertType = appMerchantEnterApplyPageVo.getLegalCertType();
                if (!StringUtils.isBlank(legalCertType)) {
                    CertTypeEnum certTypeEnum = CertTypeEnum.typeOfValue(legalCertType);
                    if (certTypeEnum != null) {
                        appMerchantEnterApplyPageVo.setLegalCertType(certTypeEnum.getName());
                    }
                }

                adminMerchantPageVo.setAppMerchantEnterApplyPageVo(appMerchantEnterApplyPageVo);
            } else {
                // 查询商家入驻数据
                List<TbBusinessEnterApplyPo> businessEnterApplyPos = businessEnterApplyMapper.selectList(new QueryWrapper<TbBusinessEnterApplyPo>()
                        .eq("del_state", 0)
                        .eq("mobile", tbMerchantPo.getMobile())
                        .orderByDesc("create_time"));
                if (!CollectionUtils.isEmpty(businessEnterApplyPos)) {
                    TbBusinessEnterApplyPo tbBusinessEnterApplyPo = businessEnterApplyPos.get(0);
                    AppMerchantEnterApplyPageVo appMerchantEnterApplyPageVo = new AppMerchantEnterApplyPageVo();
                    BeanUtils.copyProperties(tbBusinessEnterApplyPo, appMerchantEnterApplyPageVo);

                    String bankCode = appMerchantEnterApplyPageVo.getBankCode();
                    if (!StringUtils.isBlank(bankCode)) {
                        HfBankIdEnum hfBankIdEnum = HfBankIdEnum.typeOfValue(bankCode);
                        if (hfBankIdEnum != null) {
                            appMerchantEnterApplyPageVo.setBankName(hfBankIdEnum.getName());
                        }
                    }

                    // 法人证件类型
                    String legalCertType = appMerchantEnterApplyPageVo.getLegalCertType();
                    if (!StringUtils.isBlank(legalCertType)) {
                        CertTypeEnum certTypeEnum = CertTypeEnum.typeOfValue(legalCertType);
                        if (certTypeEnum != null) {
                            appMerchantEnterApplyPageVo.setLegalCertType(certTypeEnum.getName());
                        }
                    }

                    appMerchantEnterApplyPageVo.setMerchantName(tbBusinessEnterApplyPo.getBusinessName());
                    appMerchantEnterApplyPageVo.setMerchantShortName(tbBusinessEnterApplyPo.getBusinessShortName());
                    adminMerchantPageVo.setAppMerchantEnterApplyPageVo(appMerchantEnterApplyPageVo);
                }
            }

            // 银行卡信息
            MerchantBankCardVo merchantBankCardVo = merchantBankCardService.getBankCardByMerchantId(id);
            if (merchantBankCardVo != null && adminMerchantPageVo.getAppMerchantEnterApplyPageVo() != null) {
                adminMerchantPageVo.getAppMerchantEnterApplyPageVo().setCardName(merchantBankCardVo.getCardName());
                adminMerchantPageVo.getAppMerchantEnterApplyPageVo().setCardNo(merchantBankCardVo.getCardNo());
            }

            return adminMerchantPageVo;
        }
        return null;
    }

    @Override
    public Page<RelationBusinessPageVo> pageRelationBusiness(RelationBusinessPageDto relationBusinessPageDto) {
        PageHelper.startPage(relationBusinessPageDto.getPageNum(), relationBusinessPageDto.getPageSize());
        List<RelationBusinessPageVo> businessMerchantVos = businessMerchantMapper.lisRelationBusinessByDto(relationBusinessPageDto);
        PageInfo<RelationBusinessPageVo> pageInfo = new PageInfo<>(businessMerchantVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public MerchantVo getByMobile(String mobile) {
        List<TbMerchantPo> tbMerchantPos = baseMapper.selectList(new QueryWrapper<TbMerchantPo>().eq("del_state", 0)
                .eq("mobile", mobile));
        if (!CollectionUtils.isEmpty(tbMerchantPos)) {
            MerchantVo merchantVo = new MerchantVo();
            BeanUtils.copyProperties(tbMerchantPos.get(0), merchantVo);
            return merchantVo;
        }
        return null;
    }

    @Override
    public MerchantVo getMerchantById(long id) {
        TbMerchantPo tbMerchantPo = baseMapper.selectById(id);
        if (tbMerchantPo != null) {
            MerchantVo merchantVo = new MerchantVo();
            BeanUtils.copyProperties(tbMerchantPo, merchantVo);
            // 是否自有商户
            LambdaQueryWrapper<TbBusinessMerchantPo> qw = Wrappers.<TbBusinessMerchantPo>lambdaQuery()
                    .eq(TbBusinessMerchantPo::getMerchantId, tbMerchantPo.getId())
                    .eq(TbBusinessMerchantPo::getOwnState, OwnStateEnum.YES.getValue())
                    .orderByDesc(TbBusinessMerchantPo::getCreateTime)
                    .last("LIMIT 1");
            TbBusinessMerchantPo tbBusinessMerchantPo = businessMerchantMapper.selectOne(qw);
            if (tbBusinessMerchantPo != null) {
                merchantVo.setOwnState(OwnStateEnum.YES.getValue());
                merchantVo.setMasterBusinessId(tbBusinessMerchantPo.getBusinessId());
            }
            return merchantVo;
        }
        return null;
    }

    @Override
    public Boolean updateMerchant(MerchantUpdateDto merchantUpdateDto) {
        TbMerchantPo tbMerchantPo = baseMapper.selectById(merchantUpdateDto.getId());
        if (tbMerchantPo == null) {
            Throw.isBusinessException("未找到商户数据");
        }

        BeanUtils.copyProperties(merchantUpdateDto, tbMerchantPo);
        tbMerchantPo.setUpdateTime(LocalDateTime.now());
        int update = baseMapper.updateById(tbMerchantPo);
        if (update == 0) {
            Throw.isBusinessException("更新商户失败");
        }

//        redisUtil.del(String.format(RedisKeyConstant.MERCHANT_INFO_KEY, tbMerchantPo.getId()));

        return true;
    }

    @Override
    public Page<AppMerchantPageVo> pageAppMerchant(AppMerchantPageDto appMerchantPageDto) {
        Long businessId = appMerchantPageDto.getBusinessId();
        if (businessId == null) {
            // 根据userId获取商家id
            List<TbBusinessPo> tbBusinessPos = businessMapper.selectList(new QueryWrapper<TbBusinessPo>().eq("del_state", 0)
                    .eq("state", 1).eq("user_id", appMerchantPageDto.getUserId()));
            if (CollectionUtils.isEmpty(tbBusinessPos)) {
                Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
            }

            appMerchantPageDto.setBusinessId(tbBusinessPos.get(0).getId());
        }

        PageHelper.startPage(appMerchantPageDto.getPageNum(), appMerchantPageDto.getPageSize());
        List<AppMerchantPageVo> merchantPageVos = businessMerchantMapper.listAppMerchantByDto(appMerchantPageDto);
        if (!CollectionUtils.isEmpty(merchantPageVos)) {
            for (AppMerchantPageVo merchantPageVo : merchantPageVos) {
                BigDecimal totalOrderAmt = merchantPageVo.getTotalOrderAmt();
                BigDecimal totalSubsidyAmt = merchantPageVo.getTotalSubsidyAmt();
                if (totalOrderAmt == null || totalOrderAmt.compareTo(BigDecimal.ZERO) <= 0) {
                    totalOrderAmt = BigDecimal.ZERO;
                }

                if (totalSubsidyAmt == null || totalSubsidyAmt.compareTo(BigDecimal.ZERO) <= 0) {
                    totalSubsidyAmt = BigDecimal.ZERO;
                }
                merchantPageVo.setTotalOrderAmt(totalOrderAmt.add(totalSubsidyAmt));
            }
        }
        PageInfo<AppMerchantPageVo> pageInfo = new PageInfo<>(merchantPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public AppMerchantDetailVo detailAppMerchant(AppMerchantDetailDto appMerchantDetailDto) {
        Long id = appMerchantDetailDto.getId();
        Long businessId = appMerchantDetailDto.getBusinessId();
        if (businessId == null) {
            // 根据userId获取商家id
            List<TbBusinessPo> tbBusinessPos = businessMapper.selectList(new QueryWrapper<TbBusinessPo>().eq("del_state", 0)
                    .eq("state", 1).eq("user_id", appMerchantDetailDto.getUserId()));
            if (CollectionUtils.isEmpty(tbBusinessPos)) {
                Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
            }

            businessId = tbBusinessPos.get(0).getId();
            appMerchantDetailDto.setBusinessId(businessId);
        }

        TbMerchantPo tbMerchantPo = baseMapper.selectById(id);
        if (tbMerchantPo == null || tbMerchantPo.getDelState() != 0) {
            Throw.isBusinessException("未找到商户数据");
        }

        // 判断当前商家与商户是否存在绑定关系
        List<TbBusinessMerchantPo> tbBusinessMerchantPos = businessMerchantMapper.selectList(new QueryWrapper<TbBusinessMerchantPo>().eq("del_state", 0)
                .eq("business_id", businessId).eq("merchant_id", id));
        if (CollectionUtils.isEmpty(tbBusinessMerchantPos)) {
            return null;
        }
        TbBusinessMerchantPo tbBusinessMerchantPo = tbBusinessMerchantPos.get(0);

        // 查询商户的在售商品数
        Integer count = goodsApi.onGoodsCount(id).unpack();

        // 本月销售额=本月商户本金+本月商品订单补贴
        BigDecimal monthOrderAmt = BigDecimal.ZERO;
        // 本月订单数=本月核销的订单数量总和
        int monthOrderCount = 0;
        // 本月补贴金额=本月核销订单带来的补贴金额总和
        BigDecimal monthSubsidyAmt = BigDecimal.ZERO;

        LocalDate nowLocalDate = LocalDate.now();
        OrderItemDto orderItemDto = new OrderItemDto();
        orderItemDto.setBusinessId(businessId);
        orderItemDto.setMerchantId(id);
        // 本月1号
        orderItemDto.setStartVerifyTime(LocalDateUtil.toLocalDateToString(nowLocalDate.with(TemporalAdjusters.firstDayOfMonth()), Constant.YYYY_MM_DD) + " 00:00:00");
        // 本月最后一天
        orderItemDto.setEndOrderTime(LocalDateUtil.toLocalDateToString(nowLocalDate.with(TemporalAdjusters.lastDayOfMonth()), Constant.YYYY_MM_DD) + " 23:59:59");
        orderItemDto.setSubOrderStates(Collections.singletonList(SubOrderStateEnum.VERIFIED.getValue()));
        // 查询本月与指定商家关联的商户的已核销的订单项数据
        List<OrderItemVo> orderItemVos = orderItemApi.listByDto(orderItemDto).unpack();
        if (!CollectionUtils.isEmpty(orderItemVos)) {
            for (OrderItemVo orderItemVo : orderItemVos) {
                // 商户订单本金(按比例分配的用户支付的订单款)
                BigDecimal merchantAmt = orderItemVo.getMerchantAmt();
                // 商户订单补贴(该订单商场补贴的金额)
//                BigDecimal merchantSubsidyAmt = orderItemVo.getMerchantSubsidyAmt();
                // 总补贴金额
                BigDecimal totalSubsidyAmt = orderItemVo.getTotalSubsidyAmt();

                monthOrderAmt = monthOrderAmt.add(merchantAmt).add(totalSubsidyAmt);
                monthSubsidyAmt = monthSubsidyAmt.add(totalSubsidyAmt);
            }

            // 订单数
            monthOrderCount = orderItemVos.stream().map(OrderItemVo::getOrderId).collect(Collectors.toSet()).size();
        }

        AppMerchantDetailVo appMerchantDetailVo = new AppMerchantDetailVo();
        appMerchantDetailVo.setId(id);
        appMerchantDetailVo.setMerchantName(tbMerchantPo.getMerchantName());
        appMerchantDetailVo.setMerchantShortName(tbMerchantPo.getMerchantShortName());
        appMerchantDetailVo.setAvatar(tbMerchantPo.getAvatar());
        appMerchantDetailVo.setMcc(tbMerchantPo.getMcc());
        appMerchantDetailVo.setMccName(tbMerchantPo.getMccName());
        appMerchantDetailVo.setContactName(tbMerchantPo.getContactName());
        appMerchantDetailVo.setContactMobileNo(tbMerchantPo.getContactMobileNo());
        appMerchantDetailVo.setSaleGoodsCount(count == null ? 0 : count);

        appMerchantDetailVo.setMonthOrderAmt(monthOrderAmt);
        appMerchantDetailVo.setMonthOrderCount(monthOrderCount);
        appMerchantDetailVo.setMonthSubsidyAmt(monthSubsidyAmt);

        appMerchantDetailVo.setTotalOrderAmt(tbBusinessMerchantPo.getTotalOrderAmt().add(tbBusinessMerchantPo.getTotalSubsidyAmt()));
        appMerchantDetailVo.setTotalOrderCount(tbBusinessMerchantPo.getTotalOrderCount());
        appMerchantDetailVo.setTotalSubsidyAmt(tbBusinessMerchantPo.getTotalSubsidyAmt());

        return appMerchantDetailVo;
    }

    @Override
    public List<MerchantPageVo> listMerchantByIds(List<String> ids) {
        return baseMapper.listMerchantByIds(ids);
    }

    @Override
    public MerchantVo getByOpenId(String openid) {
        List<TbMerchantPo> tbMerchantPos = baseMapper.selectList(new QueryWrapper<TbMerchantPo>().eq("del_state", 0)
                .eq("openid", openid));
        if (!CollectionUtils.isEmpty(tbMerchantPos)) {
            MerchantVo merchantVo = new MerchantVo();
            BeanUtils.copyProperties(tbMerchantPos.get(0), merchantVo);
            return merchantVo;
        }
        return null;
    }

    @Override
    public Boolean updateCustomInfo(MerchantCustomUpdateDto merchantCustomUpdateDto) {
        TbMerchantPo tbMerchantPo = baseMapper.selectById(merchantCustomUpdateDto.getId());
        if (tbMerchantPo == null) {
            Throw.isBusinessException("未找到商户数据");
        }

        BeanUtils.copyProperties(merchantCustomUpdateDto, tbMerchantPo);
        tbMerchantPo.setUpdateTime(LocalDateTime.now());
        int update = baseMapper.updateById(tbMerchantPo);
        if (update == 0) {
            Throw.isBusinessException("更新商户失败");
        }

        String merchantIdRedis = String.valueOf(merchantCustomUpdateDto.getId());
        String merchantInfoRedis = redisUtil.get(String.format(RedisKeyConstant.MERCHANT_INFO_KEY, merchantIdRedis));
        if (!StringUtils.isNullOrEmpty(merchantInfoRedis)) {
            MerchantUserInfo merchantUserInfo = JSON.parseObject(merchantInfoRedis, MerchantUserInfo.class);
            merchantUserInfo.setCustomerMobile(tbMerchantPo.getCustomerMobile());
            merchantUserInfo.setCustomerWechat(tbMerchantPo.getCustomerWechat());
            merchantUserInfo.setCustomerWechatUrl(tbMerchantPo.getCustomerWechatUrl());

            merchantUserInfo.setPwdSetState(!StringUtils.isBlank(tbMerchantPo.getLoginPass()));

            // 将用户详细信息缓存到Redis
            redisUtil.set(String.format(RedisKeyConstant.MERCHANT_INFO_KEY, merchantIdRedis), JSON.toJSONString(merchantUserInfo), Constant.USER_LOGIN_TIMEOUT, TimeUnit.SECONDS);
        }

        return true;
    }

    @Override
    public Boolean updatePwd(MerchantPwdUpdateDto merchantPwdUpdateDto) {
        String originPwd = merchantPwdUpdateDto.getOriginPwd();
        String newPwd = merchantPwdUpdateDto.getNewPwd();
        String confirmPwd = merchantPwdUpdateDto.getConfirmPwd();
        String smsCode = merchantPwdUpdateDto.getSmsCode();

        if (StringUtils.isBlank(smsCode)) {
            Throw.isBusinessException("请输入验证码");
        }

        if (StringUtils.isBlank(newPwd)) {
            Throw.isBusinessException("请输入新密码");
        }

        if (StringUtils.isBlank(confirmPwd)) {
            Throw.isBusinessException("请输入确认密码");
        }

        if (!newPwd.equals(confirmPwd)) {
            Throw.isBusinessException("两次密码输入不正确");
        }

        TbMerchantPo tbMerchantPo = baseMapper.selectById(merchantPwdUpdateDto.getId());
        if (tbMerchantPo == null) {
            Throw.isBusinessException("未找到商户数据");
        }

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

//        String loginPass = tbMerchantPo.getLoginPass();
//        if (!StringUtils.isBlank(loginPass)) {
//            // 表示非首次设置密码，需要校验原始密码
//            if (StringUtils.isBlank(originPwd)) {
//                Throw.isBusinessException("请输入原始密码");
//            }
//
//            // 校验旧密码是否正确
//            if (!encoder.matches(originPwd, tbMerchantPo.getLoginPass())) {
//                Throw.isBusinessException("原始密码错误");
//            }
//        }

        String mobile = tbMerchantPo.getMobile();

        // 对手机号加锁
        String lockKey = MessageFormat.format(Constant.LOCK_FORMAT, "updatePwd:" + mobile);
        try {
            LockUtils.blockLock(lockKey, Constant.AUTO_UNLOCK_SECOND);

            // 判断短信验证码是否正确
            SmsVerifyDto smsVerifyDto = new SmsVerifyDto();
            smsVerifyDto.setCode(smsCode);
            smsVerifyDto.setMobile(mobile);
            smsVerifyDto.setType(SmsTypeEnum.SMS_UPDATE_MERCHANT_LOGIN_PWD.getValue());
            smsBiz.verify(smsVerifyDto).isSuccess();

            tbMerchantPo.setLoginPass(encoder.encode(newPwd));
            tbMerchantPo.setUpdateTime(LocalDateTime.now());
            int update = baseMapper.updateById(tbMerchantPo);
            if (update == 0) {
                Throw.isBusinessException("更新商户失败");
            }

            String merchantIdRedis = String.valueOf(tbMerchantPo.getId());
            String merchantInfoRedis = redisUtil.get(String.format(RedisKeyConstant.MERCHANT_INFO_KEY, merchantIdRedis));
            if (!StringUtils.isNullOrEmpty(merchantInfoRedis)) {
                MerchantUserInfo merchantUserInfo = JSON.parseObject(merchantInfoRedis, MerchantUserInfo.class);
                merchantUserInfo.setCustomerMobile(tbMerchantPo.getCustomerMobile());
                merchantUserInfo.setCustomerWechat(tbMerchantPo.getCustomerWechat());
                merchantUserInfo.setCustomerWechatUrl(tbMerchantPo.getCustomerWechatUrl());

                merchantUserInfo.setPwdSetState(!StringUtils.isBlank(tbMerchantPo.getLoginPass()));

                // 将用户详细信息缓存到Redis
                redisUtil.set(String.format(RedisKeyConstant.MERCHANT_INFO_KEY, merchantIdRedis), JSON.toJSONString(merchantUserInfo), Constant.USER_LOGIN_TIMEOUT, TimeUnit.SECONDS);
            }

            return true;
        } finally {
            LockUtils.unlock(lockKey);
        }
    }

    @Override
    public Integer getNewCountByDate(String startTime, String endTime) {
        return baseMapper.selectCount(new QueryWrapper<TbMerchantPo>().eq("del_state", 0).ge("create_time", startTime).le("create_time", endTime));
    }

    @Override
    public List<MerchantDetailVo> listDetailByIds(List<Long> merchantIds) {
        return baseMapper.listDetailByIds(merchantIds);
    }

    @Override
    public Boolean addMerchantAmt(MerchantAmtAddDto merchantAmtAddDto) {
        return baseMapper.merchantAmtAddDto(merchantAmtAddDto);
    }

    @Override
    public MerchantDetailVo getDetailById(Long id) {
        TbMerchantPo tbMerchantPo = baseMapper.selectById(id);
        if (tbMerchantPo != null) {
            MerchantDetailVo merchantDetailVo = new MerchantDetailVo();
            BeanUtils.copyProperties(tbMerchantPo, merchantDetailVo);
            return merchantDetailVo;
        }
        return null;
    }

    @Override
    public int subMerchantSubsidyAmt(Long id, BigDecimal tradeAmt) {
        return baseMapper.subMerchantSubsidyAmt(id, tradeAmt);
    }

    @Override
    public int subMerchantAmt(Long id, BigDecimal tradeAmt) {
        return baseMapper.subMerchantAmt(id, tradeAmt);
    }

    @Transactional
    @Override
    public Boolean updateBankCard(MerchantBankCardDto merchantBankCardDto) {
        TbMerchantPo tbMerchantPo = baseMapper.selectById(merchantBankCardDto.getMerchantId());
        if (FinancialAccountTypeEnum.PLATFORM.getValue() != tbMerchantPo.getFinancialAccountType()) {
            Throw.isBusinessException("非平台资金账户不能修改银行卡信息");
        }
        // 更新银行卡信息
        // 查询商家入驻成功记录
        BusinessEnterApplyDetailVo businessEnterApplyDetailVo = businessEnterApplyService.getSuccessEnterInfoByOpenid(tbMerchantPo.getOpenid());
        if (businessEnterApplyDetailVo == null) {
            Throw.isBusinessException("商家入驻信息不存在");
        }
        merchantBankCardDto.setBankName(HfBankIdEnum.getNameByValue(merchantBankCardDto.getBankCode()));
        merchantBankCardService.saveBankCard(merchantBankCardDto);

        return true;
    }

    @Override
    public MerchantBankCardVo getBankCard(Long merchantId) {
        MerchantBankCardVo bankCard = merchantBankCardService.getBankCardByMerchantId(merchantId);
        if (bankCard != null) {
            return bankCard;
        }
        // 如果为空，从申请记录里面查询
        TbMerchantPo tbMerchantPo = baseMapper.selectById(merchantId);
        MerchantEnterApplyVo merchantEnterApplyVo = merchantEnterApplyService.getSuccessEnterInfoByOpenid(tbMerchantPo.getOpenid());
        if (merchantEnterApplyVo != null) {
            return buildMerchantBankCardVo(merchantEnterApplyVo.getCardName(),
                    merchantEnterApplyVo.getCardNo(),
                    merchantEnterApplyVo.getBankCode());
        } else {
            // 查询商家入驻成功记录
            BusinessEnterApplyDetailVo businessEnterApplyDetailVo = businessEnterApplyService.getSuccessEnterInfoByOpenid(tbMerchantPo.getOpenid());
            if (businessEnterApplyDetailVo != null) {
                return buildMerchantBankCardVo(businessEnterApplyDetailVo.getCardName(),
                        businessEnterApplyDetailVo.getCardNo(),
                        businessEnterApplyDetailVo.getBankCode());
            }
        }

        return new MerchantBankCardVo();
    }

    private MerchantBankCardVo buildMerchantBankCardVo(String cardName, String cardNo, String bankCode) {
        MerchantBankCardVo merchantBankCardVo = new MerchantBankCardVo();
        merchantBankCardVo.setCardName(cardName);
        merchantBankCardVo.setCardNo(cardNo);
        merchantBankCardVo.setBankCode(bankCode);
        if (!StringUtils.isBlank(bankCode)) {
            String bankName = HfBankIdEnum.getNameByValue(bankCode);
            merchantBankCardVo.setBankName(bankName);
        }
        return merchantBankCardVo;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode("123456");
        System.out.println(encode);
    }
}
